import sys
import os
from time import sleep
from urllib import request
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QWidget, QFileDialog, QMessageBox
from PySide2.QtUiTools import QUiLoader
from PySide2 import QtGui
from PySide2.QtGui import QPixmap
from wenxin_api.tasks.text_to_image import TextToImage
import wenxin_api
from PyQt5 import QtCore


class Ui_Form(QWidget):
    def __init__(self, *args, obj=None, **kwargs):
        super(Ui_Form, self).__init__(*args, **kwargs)
        self.ui = QUiLoader().load('untitled.ui')

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(603, 367)
        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(10, 20, 571, 331))
        self.textEdit.setAccessibleName("")
        self.textEdit.setObjectName("textEdit")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "相关信息"))
        self.textEdit.setHtml(_translate("Form",
                                         "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                         "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                         "p, li { white-space: pre-wrap; }\n"
                                         "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
                                         "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:16pt;\">版本号：1.0</span></p>\n"
                                         "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:16pt;\">发布日期：2022.8.9</span></p>\n"
                                         "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:16pt;\">开发者：ZhangHan</span></p>\n"
                                         "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:16pt;\">开发者邮箱：944211286@qq.com</span></p>\n"
                                         "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:16pt;\">(欢迎您将使用建议及问题反馈到开发者邮箱）</span></p>\n"
                                         "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"))


class Window_main(QWidget):
    def __init__(self, *args, obj=None, **kwargs):
        super(Window_main, self).__init__(*args, **kwargs)
        self.ui2 = QUiLoader().load('main.ui')
        # 变量
        self.text = ""
        self.style1 = ""
        self.AK = ""
        self.SK = ""
        self.mylist = []
        self.im = {}
        self.ui2.pushButton.clicked.connect(self.api)
        self.ui2.pushButton_2.clicked.connect(self.upload)
        self.ui2.imlist.itemClicked.connect(self.btClick)
        self.ui2.label_5.clear()
        self.ui2.actionban.triggered.connect(self.show_ban)
        self.child_window = Ui_Form()
        # self.run_thread = run_theard()

    def show_ban(self):
        self.child_window.ui.show()

    # 实现点击item显示一张图片
    def btClick(self):
        self.show_im(self.ui2.imlist.currentItem().text())

    # api
    def api(self):
        self.AK = self.ui2.lineEdit.text()
        self.SK = self.ui2.lineEdit_2.text()
        if self.AK == "" or self.SK == "":
            QMessageBox.question(self, '提示', '请输入API', QMessageBox.Yes | QMessageBox.No,
                                 QMessageBox.No)
        else:
            self.ui2.textBrowser.append("<h4>" + self.AK + "API Key上传成功</h4>")
            self.ui2.textBrowser.append("<h4>" + self.SK + "Secret Key上传成功</h4>")

    # 显示图片
    def show_im(self, im):
        self.ui2.label_5.setText(im)  # item.text()=3.bmp
        pix = QPixmap('images/' + im)
        self.ui2.label_5.setPixmap(pix)
        self.ui2.label_5.setScaledContents(True)

    # 读取图片列表
    def read(self):
        path = "images"
        self.mylist = os.listdir(path)
        for i in range(len(self.mylist)):
            self.ui2.imlist.addItem(self.mylist[i])

    # 描述文本及风格
    def upload(self):
        is_have = False
        self.text = self.ui2.lineEdit_3.text()
        self.style1 = self.ui2.lineEdit_4.text()
        stylelist = ["油画", "水彩画", "卡通", "粉笔画", "儿童画", "蜡笔画"]
        for i in range(len(stylelist)):
            if self.style1 == stylelist[i]:
                is_have = True
        if is_have == False:
            QMessageBox.question(self, '提示', '请输入正确的图片风格', QMessageBox.Yes | QMessageBox.No,
                                 QMessageBox.No)
        elif self.text == "":
            QMessageBox.question(self, '提示', '请输入描述文本', QMessageBox.Yes | QMessageBox.No,
                                 QMessageBox.No)
        elif self.AK == "" or self.SK == "":
            QMessageBox.question(self, '提示', '请先输入API', QMessageBox.Yes | QMessageBox.No,
                                 QMessageBox.No)
        else:
            self.ui2.textBrowser.append("<h4>" + self.text + "描述文本已上传</h4>")
            self.ui2.textBrowser.append("<h4>" + self.style1 + "图片风格已上传</h4>")
            self.ui2.textBrowser.append("<h4>请等待约60秒</h4>")
            self.my_main()

    # 作画
    def my_main(self):

        wenxin_api.ak = self.AK
        wenxin_api.sk = self.SK
        input_dict = {
            "text": self.text,
            "style": self.style1
        }
        # self.run_thread.start()
        self.im = TextToImage.create(**input_dict)
        for i in range(len(self.im['imgUrls'])):
            self.save_im(self.im['imgUrls'][i])
        self.read()

    # 将完成的画作保存到本地
    def save_im(self, url):
        path = "images"
        if not os.path.exists(path):
            os.makedirs(path)
        imgpath = path + '//' + os.path.split(url)[1] + '.png'
        request.urlretrieve(url, imgpath)


# class run_theard(QThread):
#     def __init__(self):
#         super(run_theard, self).__init__()

#     def run(self):
#         Window_main
#         textBrowser.append("<h4>请等待约60秒</h4>")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myWin = Window_main()
    myWin.ui2.show()
    sys.exit(app.exec_())
